package com.yhd.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.yhd.gmall.common.constant.RedisConst;
import com.yhd.gmall.common.result.Result;
import com.yhd.gmall.common.util.IpUtil;
import com.yhd.gmall.model.user.UserInfo;
import com.yhd.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author yhd
 * @createtime 2020/9/25 19:31
 */
@RestController
@RequestMapping("/api/user/passport")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request, HttpServletResponse response){
        UserInfo info = userService.login(userInfo);
        if (info!=null){
            String token = UUID.randomUUID().toString().replace("-", "");
            Map<String,Object> map=new HashMap<>();
            map.put("nickName", info.getNickName());
            map.put("token", token);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId",info.getId().toString());
            jsonObject.put("ip", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,jsonObject.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }else {
            return Result.fail("用户名或密码错误！");
        }
    }
    /**
     * 退出登录
     */
    @GetMapping("logout")
    public  Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
        return Result.ok();
    }
}
